<?php
/*
 * @Author: your name
 * @Date: 2020-06-29 09:28:29
 * @LastEditTime: 2020-09-30 17:59:35
 * @LastEditors: 天羽落星辰
 * @Description: In User Settings Edit
 * @FilePath: \WWW\frx\application\admin\controller\user\User.php
 */

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\admin\model\Contract as ModelContract;
use think\Db;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'username';   //快速搜索默认字段



    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $tpath = '';
            $groups = $this->auth->getGroupIds($this->auth->id);
            if(in_array(4,$groups) || in_array(7,$groups)){
                $user_id = db('user')->where('username',$this->auth->username)->value('id');
                if($user_id){
                    $username = db('user')->where("FIND_IN_SET({$user_id},tpath)")->column('username');
                    $username[] = $this->auth->username;
                    $total = $this->model
                    ->with('group')
                        ->where($where)
                    ->order($sort, $order)
                    ->whereIn('username',$username)
                        ->count();
                    $list = $this->model
                    ->with('group')
                        ->where($where)
                        ->whereIn('username',$username)
                        ->order($sort, $order)
                        ->limit($offset, $limit)
                        ->select();
                }else{
                    $result = array("total" => 0, "rows" => []);
                    return json($result);
                }
            }else{
                $total = $this->model
                    ->with('group')
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
                $list = $this->model
                    ->with('group')
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }

            foreach ($list as $k => $v) {
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 赠送合约
     */
    public function give_contract($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    $contract = ModelContract::get($params['contract_id']);
                    $money = $contract['money'];
                    // if(!$money){
                    //     throw new \Exception("请输入投资金额",1);
                    // }

                    $result = db('order')->insert([
                        'uid' => $row['id'],
                        'uname' => $row['username'],
                        'danhao' => orderSn(),
                        'price' => $money,
                        'shouyi' => $contract['total_revenue'],
                        'zhouqi' => $contract['day'],
                        'contract_id' => $row['id'],
                        'overtime' => strtotime("+" . $contract['day'] . " day"),
                        'zt' => 1,
                        'give' => 1, // 系统赠送合约
                        'createtime' => time(),
                    ]);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('赠送合约成功');
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign('groupList', build_select('row[contract_id]', \app\admin\model\Contract::column('id,money'), '', ['class' => 'form-control selectpicker']));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 修改F等级
     */
    public function f_level($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    // dump($params);die;
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('修改F等级成功');
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        // $this->view->assign('groupList', build_select('row[contract_id]', \app\admin\model\Contract::column('id,money'), '', ['class' => 'form-control selectpicker']));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 查看
     */
    public function tid_partner()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $username = '';
            // $wyh777  = 'wyh777';
            $user = db('user')->field('id,username,tid,tpath')->where('username',input('search'))->find();
            // $user = db('user')->field('id,username,tid,tpath')->where('username',$wyh777)->find();

            if($user){
                $tpath = array_reverse(explode(',',$user['tpath']));
                foreach($tpath as $v){
                    $user_name = db('user')->where('id',$v)->value('username');
                    if(isset(config('site')['partner'][$user_name])){
                        $username = $user_name;
                        break;
                    }elseif(isset(config('site')['partner'][strtoupper($user_name)])){
                        $username = strtoupper($user_name);
                        break;
                    }
                }
            }

            $total = $this->model
                ->where('username',$username)
                ->with('group')
                ->order($sort, $order)
                ->count();
            $list = $this->model
            ->where('username',$username)
                ->with('group')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? $v->avatar : '/assets/img/frx.png';
                $v->partner = config('site')['partner'][$username].'%';
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->assignconfig("partner",config('site.partner'));
        return $this->view->fetch();
    }
}
